﻿using DLL.Net.MS.Models;
using DLL.NET50.DB.MS.AdviceAndDrug;
using DLL.Net60.AdviceLabel.Entity;
using DLL.NET60.DB.MS.Entity.DTO;
using DLL.NET70.Infrastructure.EventAggregator;
using DLL.NET70.Infrastructure.Prism.MVVM;
using DLL.Standard.Infrastructure.Entity;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;

namespace Module.AutoRun.ViewModels
{
    public class PUC_ShowAdviceLabel6ViewModel : CMVVMBase, IRegionMemberLifetime
    {
        #region varialbe

        private CAdviceLabels _Labels = new CAdviceLabels();

        public CAdviceLabels Labels
        {
            get { return _Labels; }
            set { SetProperty(ref _Labels, value); }
        }

        #endregion varialbe

        #region navigate

        public bool KeepAlive
        {
            get
            {
                //return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
                return false;//
            }
        }

        //导航后目的页面触发，一般用于初始化或者接受上页面的传递参数
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            var reobj = navigationContext.Parameters["canUsedStation"] as string;
            if (reobj != null)
            {
                string[] arr = reobj.Split('-');
                for (int i = 0; i < arr.Length; i++)
                {
                    Labels.ItemSource[i].Enable = int.Parse(arr[i]);
                }
            }
            journal = navigationContext.NavigationService.Journal;
            GoForwardCommand.RaiseCanExecuteChanged();
            GoBackCommand.RaiseCanExecuteChanged();
        }

        #endregion navigate

        private IEventAggregator _eventAggregator;

        public PUC_ShowAdviceLabel6ViewModel(IRegionManager regionManager,
            IEventAggregator eventAggregator,
            IContainerExtension container
            ) : base(regionManager, eventAggregator)
        {
            _eventAggregator = eventAggregator;
        }

        public override void Loaded()
        {
            _eventAggregator.GetEvent<CMS_ShowLabelsMsgEvent>().Subscribe(ShowLabels_ReceiveMsg);//注册消息接收相应函数
            _eventAggregator.GetEvent<CMS_SetAdviceLabelEnableMsgEvent>().Subscribe(SetLabels_ReceiveMsg);//注册消息接收相应函数
            _eventAggregator.GetEvent<CCommandMessageEvent>().Subscribe(ReCommandMsg);//注册消息接收相应函数
            base.Loaded();
        }

        public override void UnLoaded()
        {
            _eventAggregator.GetEvent<CMS_ShowLabelsMsgEvent>().Unsubscribe(ShowLabels_ReceiveMsg);//注册消息接收相应函数
            _eventAggregator.GetEvent<CMS_SetAdviceLabelEnableMsgEvent>().Unsubscribe(SetLabels_ReceiveMsg);//注册消息接收相应函数
            base.UnLoaded();
        }

        public void SetLabels_ReceiveMsg(CMS_SetAdviceLabelEnableMsg adviceLabel)
        {
            // Obj = adviceLabel;
            for (int i = 0; i < Labels.ItemSource.Count; i++)
            {
                Labels.ItemSource[i].Enable = adviceLabel.EnableLabels[i];
            }
        }

        private void ReCommandMsg(CCommandMessage cmdMsg)
        {
            if (MSDM_CmdStr.Clear == cmdMsg.CommandStr)
            {
                //清空瓶贴
                ClearLabels();
            }
            else if ((MSDM_CmdStr.ReplaceInjectorOver == cmdMsg.CommandStr))
            {
                //换针
                currentUsedSolvent = new string[6];
                InjectorIsNew = true;//注射器已经更换
            }
            else if ((MSDM_CmdStr.Runing == cmdMsg.CommandStr))
            {
                //换针
                InjectorIsNew = false;//注射器已经
            }
        }

        private void ClearLabels()
        {
            for (int ColID = 0; ColID < StationColNum; ColID++)
            {
                if (Labels.ItemSource[ColID].Enable == 1)
                {
                    //这个瓶贴位置启用了
                    //这个瓶贴位置没有医嘱
                    Labels.ItemSource[ColID].AdviceHadStop = -1;
                }
            }
        }

        public CMS_AdviceAndDrugs advicesForFlush = new CMS_AdviceAndDrugs();

        private void ShowLabels_ReceiveMsg(CMS_ShowLabelsMsg scanBarMsg)
        {
            advicesForFlush = scanBarMsg.adviceAndDrugs;
            if (scanBarMsg.CommandStr == MSDM_CmdStr.AdviceStop)
            {
                ShowAdviceStop(scanBarMsg);
            }
            else if (scanBarMsg.CommandStr == MSDM_CmdStr.AdviceOK)
            {
                DeviceConnectkMode = scanBarMsg.ConnectMode;
                RefreshBottleLable();
            }
            else if (scanBarMsg.CommandStr == MSDM_CmdStr.Clear)
            {
                ClearLabels();
            }
        }

        private int DeviceConnectkMode = 1;
        private int StationColNum = 6;

        public string[] currentUsedSolvent = new string[6];

        //更新瓶贴显示
        private void ShowAdviceStop(CMS_ShowLabelsMsg scanBarMsg)
        {
            if (advicesForFlush != null)
            {
                int ColID = scanBarMsg.LableID;
                int stopID = Convert.ToInt32(scanBarMsg.value);
                Labels.ItemSource[ColID].bottleNo = scanBarMsg.ScanBar;
                Labels.ItemSource[ColID].AdviceHadStop = 1;//停医嘱
                Labels.ItemSource[ColID].StopAdviceID = stopID;
            }
        }

        public void RefreshBottleLable()
        {
            try
            {
                //添加刷新 条码返回状态
                int count = advicesForFlush.adviceAndDrugs.Count();
                for (int ColID = 0; ColID < count; ColID++)
                {
                    if (Labels.ItemSource[ColID].Enable == 1)
                    {
                        if (advicesForFlush.adviceAndDrugs[ColID].Enable == 1)
                        {
                            if (DeviceConnectkMode == 0)
                            {
                                //文件模式
                                WorkFile_SetValueToBottleLable(ColID);
                                SetBottleLableBackGround(ColID);
                            }
                            else
                            {
                                //没有停医嘱
                                ScanBar_SetValueToBottleLable(ColID);
                                ScanBar_SetBottleLableBackGround(ColID);
                            }
                        }
                        else
                        {
                            Labels.ItemSource[ColID].AdviceHadStop = -1;
                        }
                    }
                }
                //当医嘱小于最大的站数时，没有医嘱的瓶贴不显示
                if (DeviceConnectkMode == 0)
                {
                    //单机模式
                    for (int ColID = 0; ColID < StationColNum; ColID++)
                    {
                        if (Labels.ItemSource[ColID].Enable == 1)
                        {
                            //这个瓶贴位置启用了
                            if (advicesForFlush.adviceAndDrugs[ColID].Enable == 0)
                            {
                                //这个瓶贴位置没有医嘱
                                Labels.ItemSource[ColID].AdviceHadStop = -1;
                            }
                        }
                    }
                }
                else
                {
                    for (int ColID = 0; ColID < 6; ColID++)
                    {
                        if (Labels.ItemSource[ColID].Enable == 1)
                        {
                            if (advicesForFlush.adviceAndDrugs[ColID].Enable == 0)
                            {
                                Labels.ItemSource[ColID].AdviceHadStop = -1;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogMessage(e.Message);
            }
        }

        private void WorkFile_SetValueToBottleLable(int ColID)
        {
            SetCommonBottleLable(ColID);
            CMS_AdviceAndDrug advice = advicesForFlush.adviceAndDrugs[ColID];
            SetBottleLableDose(advice, ColID);
            Labels.ItemSource[ColID].SolventType = 0;//溶媒没有改变
            Labels.ItemSource[ColID].batch = "1";
        }

        private void ScanBar_SetValueToBottleLable(int ColID)
        {
            try
            {
                SetCommonBottleLable(ColID);
                Labels.ItemSource[ColID].areaName = advicesForFlush.adviceAndDrugs[ColID].pivasAdvicePatient.AREA_NAME;//病区
                Labels.ItemSource[ColID].patientName = advicesForFlush.adviceAndDrugs[ColID].pivasAdvicePatient.PATIENT_NAME;//病人名称
                Labels.ItemSource[ColID].bedNum = advicesForFlush.adviceAndDrugs[ColID].pivasAdvicePatient.BED_NO;//床位号

                Labels.ItemSource[ColID].bottleNo = advicesForFlush.adviceAndDrugs[ColID].pivasAdvicePatient.BOTTLE_NO;//瓶贴号
                int dose = (int)advicesForFlush.adviceAndDrugs[ColID].Solvent.DOSE;
                Labels.ItemSource[ColID].soventSpection = advicesForFlush.adviceAndDrugs[ColID].Solvent.DRUG_NAME + "/" + advicesForFlush.adviceAndDrugs[ColID].Solvent.SPECIFICATION;//溶媒
                string batchCode = advicesForFlush.adviceAndDrugs[ColID].pivasAdvicePatient.BATCH_CODE;
                string sbatchCode = Regex.Replace(batchCode, "[^0-9]", "");
                Labels.ItemSource[ColID].batch = batchCode;//批次
                CMS_AdviceAndDrug advice = advicesForFlush.adviceAndDrugs[ColID];
                SetBottleLableDose(advice, ColID);
            }
            catch (Exception e)
            {
                LogMessage("显示医嘱出现异常：" + e.Message);
            }
        }

        private void ScanBar_SetBottleLableBackGround(int ColID)
        {
            int count = advicesForFlush.adviceAndDrugs.Count();
            bool solventIsChange = SolvenIsChange(advicesForFlush.adviceAndDrugs[ColID], ColID);
            if (true == solventIsChange)
            {
                Labels.ItemSource[ColID].SolventType = 1;//溶媒发生改变
                if (ColID == (count - 1))
                {
                    //最后一个医嘱
                    //ShowRunState("溶媒发生变化！");
                }
            }
            else
            {
                int d = (int)advicesForFlush.adviceAndDrugs[ColID].adviceSolvent.DOSE - (int)advicesForFlush.adviceAndDrugs[ColID].adviceSolvent.REALDOSE;
                Labels.ItemSource[ColID].OutSolvent = d;
                if (d > 0)
                {
                    Labels.ItemSource[ColID].SolventType = 2;//溶媒没有改变，但需要抽出溶媒
                    if (ColID == (count - 1))
                    {
                        //最后一个医嘱
                        //ShowRunState("溶媒需要抽出" + d.ToString("0.##") + "ml");
                    }
                }
                else
                {
                    Labels.ItemSource[ColID].SolventType = 0;//溶媒没有发生改变
                    if (ColID == (count - 1))
                    {
                        //最后一个医嘱
                        //ShowRunState("扫码正常", LogLevel.Information);
                    }
                }
            }
            SetBottleLableBackGround(ColID);
        }

        //判断溶媒是否改变
        private bool InjectorIsNew = true;

        private bool SolvenIsChange(CMS_AdviceAndDrug advice, int ColID)
        {
            string solventName = advice.Solvent.DRUG_NAME.Trim();
            bool solventIsChange = false;
            bool oislhn = false;
            ////判断有没有换针
            if (string.IsNullOrEmpty(currentUsedSolvent[ColID]))
            {
                //没有记录溶媒信息
                currentUsedSolvent[ColID] = solventName;
                solventIsChange = false;
            }
            else
            {
                //已经记录溶媒信息
                if (currentUsedSolvent[ColID].Contains("氯化钠"))
                {
                    oislhn = true;
                }
                else
                {
                    oislhn = false;
                }
                bool nislhn = false;
                if (solventName.Contains("氯化钠"))
                {
                    nislhn = true;
                }
                else
                {
                    nislhn = false;
                }
                if (oislhn != nislhn)
                {
                    //溶媒发生改变
                    solventIsChange = true;
                }
                else
                {
                    solventIsChange = false;
                }
            }
            return solventIsChange;
        }

        private void SetBottleLableBackGround(int ColID)
        {
            //if (0 == Labels.ItemSource[ColID].SolventType)
            //{
            //    //溶媒没有发生改变
            //    //if (Lableobjs.ItemSource[ColID].batch == 1)
            //    //{
            //    //    // 是第一批次
            //    //    Lableobjs.ItemSource[ColID].SolventlBackground = "YellowGreen";
            //    //}
            //    //else
            //    //{
            //    //    //不是第一批次
            //    //    Lableobjs.ItemSource[ColID].SolventlBackground = "Pink";
            //    //}
            //    Labels.ItemSource[ColID].SolventlBackground = "#FF40A033";
            //}
            //else
            if (1 == Labels.ItemSource[ColID].SolventType)
            {
                //溶媒发生改变
                Labels.ItemSource[ColID].SolventlBackground = "Red";
            }
            else if (2 == Labels.ItemSource[ColID].SolventType)
            {
                //溶媒需要抽出
                Labels.ItemSource[ColID].SolventlBackground = "Yellow";
            }
            else
            {
                //溶媒没有发生改变
                if ((Labels.ItemSource[ColID].batch == "1")||(Labels.ItemSource[ColID].batch == "01"))
                {
                    // 是第一批次
                    Labels.ItemSource[ColID].SolventlBackground = "#FF40A033";
                }
                else
                {
                    //不是第一批次
                    Labels.ItemSource[ColID].SolventlBackground = "#FFA2E4AF";
                }
            }
        }

        private void SetBottleLableDose(CMS_AdviceAndDrug advice, int ColID)
        {
            {
                float allUsedDrugDose = Convert.ToSingle(advice.GetRealDose().ToString("F3"));
                float allDrugDose = Convert.ToSingle((advice.GetDose().ToString("F3")));
                if (allUsedDrugDose < allDrugDose)
                {
                    //非整只
                    Labels.ItemSource[ColID].fzzMode = 1;

                    Labels.ItemSource[ColID].drugRealDose = advice.GetRealDose().ToString("f3") + GetDoseUnit(advice.adviceDrug[0].DOSE_UNIT);
                    Labels.ItemSource[ColID].OutVolume = advice.GetFZZOutVolume().ToString("f3");
                    if (advice.Drugs[0].NEEDLE_TYPE == 0)
                    {
                        //稀释溶媒体积
                        Labels.ItemSource[ColID].DiluteVolume = advice.GetFZZInVolume().ToString("f3");
                    }
                    else
                    {
                        //稀释溶媒体积
                        Labels.ItemSource[ColID].DiluteVolume = "0";
                    }
                }
                else
                {
                    Labels.ItemSource[ColID].fzzMode = 0;
                    Labels.ItemSource[ColID].drugRealDose = advice.GetRealDose().ToString("f3") + GetDoseUnit(advice.Drugs[0].DOSE_UNIT.ToString());
                    if (advice.Drugs[0].NEEDLE_TYPE == 0)
                    {
                        //粉针
                        Labels.ItemSource[ColID].DiluteVolume = (advice.Drugs[0].flush_Groups[0].flush_Params[0].SolventVolume).ToString("f3");//稀释溶媒体积
                        Labels.ItemSource[ColID].OutVolume = (advice.Drugs[0].flush_Groups[0].flush_Params[0].SolventVolume).ToString("f3");//这个地方需要添加非整只判断
                    }
                    else if (advice.Drugs[0].NEEDLE_TYPE == 1)
                    {
                        //水针
                        Labels.ItemSource[ColID].DiluteVolume = "0";//稀释溶媒体积
                        Labels.ItemSource[ColID].OutVolume = (advice.Drugs[0].BOTTLE_VOLUME).ToString("f3");//这个地方需要添加非整只判断
                    }
                }
            }
        }

        private string GetDoseUnit(string unit)
        {
            string doseUnit = "";
            if (unit != null)
            {
                if ((unit.ToUpper() == "G") || (unit.ToUpper() == "GM"))
                {
                    doseUnit = "g";
                }
                else
                {
                    doseUnit = unit;
                }
            }
            return doseUnit;
        }

        private void SetCommonBottleLable(int ColID)
        {
            Labels.ItemSource[ColID].AdviceHadStop = advicesForFlush.adviceAndDrugs[ColID].AdviceHadStop;//停嘱
            Labels.ItemSource[ColID].drugCode = advicesForFlush.adviceAndDrugs[ColID].Drugs[0].DRUG_CODE;//药品编码
            Labels.ItemSource[ColID].drugName = advicesForFlush.adviceAndDrugs[ColID].Drugs[0].DRUG_NAME;//药品名称
            Labels.ItemSource[ColID].drugCount = advicesForFlush.adviceAndDrugs[ColID].GetRealQuatity().ToString();//药品数量
            //Lableobjs.ItemSource[ColID].surplusDose = RemainDrugDose[ColID].ToString(); //autoRun.RemainDrugDose[ColID].ToString();
        }
    }
}